package utils;

import static com.qb.devserv.MainActivity.mActivity;
import static com.qb.devserv.MainService.mService;

import android.app.admin.DevicePolicyManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Environment;

import android.os.Handler;
import android.os.Looper;
import android.os.RecoverySystem;
import android.widget.Toast;

import com.qb.devserv.DialogActivity;
import com.qb.devserv.SystemActivity;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Date;

public class DevActionUtil {
    // 获取固件下载路径
    public static String getRomPath() {
        return Build.VERSION.SDK_INT >= 30?"/storage/emulated/0/Download/":"/data/media/0/Download/";
    }
    // 关机
    public static void powerDown(Context ctx, String flag, Boolean isConfirm) {
        if (!isConfirm) {
            try {
                Runtime.getRuntime().exec("reboot -p");
                // 以下方法星河有效，华诚无效
//                Intent intent = new Intent("android.intent.action.shutdown");
//                ctx.sendBroadcast(intent);
            } catch (Exception e) {
                Toast.makeText(ctx, "重启失败："+e.getMessage(), Toast.LENGTH_LONG).show();
            }
        } else {
            showAppDialog(ctx,flag,"");
        }
    }
    // 重启
    public static void reSet(Context ctx,String flag,Boolean isConfirm) {
        if (!isConfirm) {
            try {
                Runtime.getRuntime().exec("reboot");
                // 以下方法星河有效，华诚无效
//                Intent intent = new Intent("android.intent.action.pubds_reboot");
//                ctx.sendBroadcast(intent);
            } catch (Exception e) {
                Toast.makeText(ctx, "重启失败："+e.getMessage(), Toast.LENGTH_LONG).show();
            }
        } else {
            showAppDialog(ctx,flag,"");
        }
    }
    // 下载升级固件包
    public static void updateDownload(Context ctx,String flag,String url,Boolean isConfirm) {
        MyUtil.showLog("sysUpdate",url);
        String name = "update.zip";
        File f = getFileByPath(getRomPath()+name,true);
        MyUtil.showLog("sysUpdate",f);
        if (f==null) {
            downLoad(ctx,url,name,"rom",isConfirm);
        } else {
            if (isConfirm) {
                showAppDialog(ctx,flag,"");
            } else {
                showSysActivity(ctx,flag);
            }
        }
    }
    // 恢复出厂设置
    public static void reFactory(Context ctx,String flag, Boolean isConfirm) {
        if (!isConfirm) {
            Intent intent = new Intent("android.intent.action.FACTORY_RESET");
            MyUtil.showLog("reFactory", Build.VERSION.SDK_INT);

            if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O) {
                intent = new Intent("android.intent.action.MASTER_CLEAR"); //8.0
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
                intent.setPackage("android");
            }
            //以上区分不同系统
            intent.putExtra("android.intent.extra.REASON", "FactoryMode");
            //是否擦除SdCard
            intent.putExtra("android.intent.extra.WIPE_EXTERNAL_STORAGE", false);
            intent.putExtra("android.intent.extra.EXTRA_WIPE_ESIMS", true);
            MyUtil.showLog("reFactory", intent);
            ctx.sendBroadcast(intent);
            String sn = DevInfoUtil.getSN();
            //mService.mu.publishMessage("/MyTest/DevServe/DevQuery/ReQuery",sn);
            MyUtil.showLog("reFactory", "Done");
        } else {
            showAppDialog(ctx,flag,"");
        }
    }
    // 应用安装、卸载、启动
    public static void appAction(Context ctx,String action,String name,String url,Boolean isConfirm) {
        if (action.equals("install")) {
            downLoad(ctx,url,name+".apk","app",isConfirm);
        }
        if (action.equals("uninstall")) {
            String r = "";
            if (isConfirm) {
                r = AppUtil.uninstallApk(ctx,name);
            } else {
//                r = AppUtil.uninstallApkSilent(name);
//                MyUtil.showLog("uninstallApkSilent DevActionUtil",r);
//                MyUtil.showLog("uninstallApkSilent checkApplication",AppUtil.checkApplication(ctx,name));
//                r = AppUtil.uninstallApkSilent2(name);
//                MyUtil.showLog("uninstallApkSilent2 DevActionUtil",r);
//                MyUtil.showLog("uninstallApkSilent2 checkApplication",AppUtil.checkApplication(ctx,name));
                r = AppUtil.uninstallApkSilent3(ctx,name);  // 华诚3588用此方法
                MyUtil.showLog("uninstallApkSilent3 DevActionUtil",r);
//                MyUtil.showLog("uninstallApkSilent3 checkApplication",AppUtil.checkApplication(ctx,name));
//                r = AppUtil.uninstallApkSilent5(ctx,name);
//                MyUtil.showLog("uninstallApkSilent5 DevActionUtil",r);
//                MyUtil.showLog("uninstallApkSilent5 checkApplication",AppUtil.checkApplication(ctx,name));
//                r = AppUtil.uninstallApkSilent4(ctx,name);
//                MyUtil.showLog("uninstallApkSilent4 DevActionUtil",r);
//                MyUtil.showLog("uninstallApkSilent4 checkApplication",AppUtil.checkApplication(ctx,name));
            }
            MyUtil.showLog("uninstall app", r);
            if (r.equals("success")) {
                //Looper.prepare();
                new Handler().postDelayed(()-> {
                    mActivity.upLoadDevDetail();
                },3000);
                //Looper.loop();
            } else {
                DevActionUtil.cancelAppDialog(ctx,"应用卸载失败",r);
            }
        }
        if (action.equals("autorun")) {
            //AppUtil.startAppByPackage(ctx,name);
            SharedPreferences SP = ctx.getSharedPreferences("dev_mgt_setting", ctx.MODE_PRIVATE);
            SharedPreferences.Editor edit = SP.edit();
            String autorunApp  = isConfirm?name:"";
            MyUtil.showLog("setAutorunApp",autorunApp);
            edit.putString("autorunApp", autorunApp);
            edit.apply();
            mActivity.upLoadDevDetail();
        }
    }

    // 显示appdialog
    public static void showAppDialog(Context ctx,String flag,String p1) {
        String t = "来自终端管理平台的指令";
        String m = "";
        if (flag.equals("powerdown")) m = "是否确认关机";
        if (flag.equals("reset")) m = "是否确认重启此设备";
        if (flag.equals("update")) m = "是否确认升级固件";
        if (flag.equals("reUpdate")) {
            t = "升级固件下载失败";
            m = "是否重新下载";
        }
        if (flag.equals("factory")) m = "是否确认恢复出厂设置";
        Intent intent = new Intent(ctx, DialogActivity.class);
        intent.putExtra("flag",flag);
        intent.putExtra("parm1",p1);
        intent.putExtra("title",t);
        intent.putExtra("msg",m);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        ctx.startActivity(intent);
    }
    // appdialog点击了确认
    public static void okAppDialog(Context ctx,String flag,String p1) {
        if (flag.equals("powerdown")) powerDown(ctx,flag,false);
        if (flag.equals("reset")) reSet(ctx,flag,false);
        if (flag.equals("update")) showSysActivity(ctx,flag);
        if (flag.equals("reUpdate")) updateDownload(ctx,flag,p1,true);
        if (flag.equals("factory")) reFactory(ctx,flag,false);
    }
    // appdialog点击了取消
    public static void cancelAppDialog(Context ctx,String flag,String p1) {
        MyUtil.showLog("cancelAppDialog flag="+flag,p1);
        Looper.prepare();
        Toast.makeText(ctx, flag+":"+p1, Toast.LENGTH_LONG).show();
        Looper.loop();
    }

    // 显示系统级提示界面
    public static void showSysActivity(Context ctx,String flag) {
        Intent intent = new Intent(ctx, SystemActivity.class);
        intent.putExtra("flag",flag);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        ctx.startActivity(intent);
    }

    //下载文件
    public static void downLoad(Context ctx,String url,String name,String flag,Boolean isConfirm) {
        String destFileDir = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "Download/";
        final int[] currentProgress = {0};
        if(MyUtil.isFolderExists(destFileDir)) {
            MyUtil.showLog("downLoad","开始下载:"+name);
            DownloadUtil dlu = new DownloadUtil(url);
            dlu.download(destFileDir, name, new DownloadUtil.OnDownloadListener() {
                @Override
                public void onDownloadSuccess(File file) {
                    MyUtil.showLog("downLoad","下载完成");
                    if (flag.equals("rom")) {
                        if (isConfirm) {
                            showAppDialog(ctx,"update","");
                        } else {
                            showSysActivity(ctx,"update");
                        }
                    }
                    if (flag.equals("app")) {
                        String r = "";
                        if (isConfirm) {
                            r = AppUtil.installApk(ctx,destFileDir+name);
                        } else {
                            r = AppUtil.installApkSilent(ctx, destFileDir+name);
                        }
                        MyUtil.showLog("install app", r);
                        if (r.equals("success")) {
//                            if ()  如果安装的是企帮终端服务  启动他
                            Looper.prepare();
                            new Handler().postDelayed(()-> {
                                mActivity.upLoadDevDetail();
                            },3000);
                            Looper.loop();
                        } else {
                            DevActionUtil.cancelAppDialog(ctx,"应用安装失败",r);
                        }
                    }
                    if (flag.equals("bootanimation")) {
                        Looper.prepare();
                        new Handler().postDelayed(()-> {
                            setAnimationByRoot(ctx,1);
                        },3000);
                        Looper.loop();
                    }
                }

                @Override
                public void onDownloading(int progress) {
                    //下载进行中展示进度
                    String title = "正在下载"+name;
                    if (flag.equals("rom")) title = "正在下载升级固件";
                    if (progress > currentProgress[0]) {
                        MyUtil.showLog("downLoad","下载进度:"+progress);
                        MyUtil.showLog("downLoad progress="+progress,currentProgress[0]);
                        currentProgress[0] = progress;
                        MyUtil.showNotifaction(ctx,10010,title,"下载进度:" + (int) (progress) + "%",progress,"DOWN_LOAD_ROM");
                    }
                }

                @Override
                public void onDownloadFailed(Exception e) {
                    //下载异常进行相关提示操作
                    MyUtil.showLog("downLoad",name+"下载失败"+e);
                    if (flag.equals("rom")) showAppDialog(ctx,"reUpdate",url);
                }
            });
        } else {
            MyUtil.showLog("downLoad",name+"下载失败"+"目录不存在");
            if (flag.equals("rom")) showAppDialog(ctx,"reUpdate",url);
        }
    }

    //删除文件
    public static Boolean delFile(String filePath) {
        File f = getFileByPath(filePath,false);
        try {
            f.delete();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    // 获取文件
    public static File getFileByPath(String filePath,Boolean reNull) {
        File updateFile = null;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            updateFile = new File(filePath);
            boolean isExists = updateFile.exists();
            MyUtil.showLog("getUpdateFile isExists="+isExists,filePath);
            if (isExists) {
                return updateFile;
            } else {
                if (reNull) return null;
            }
        }
        return updateFile;
    }

    /*
    * 开机画面设置
    * */
    // 判断是什么主板然后执行对应命令  flag: 2 下载开机画面，1 设置开机画面，0 清除开机画面，-1 不同主板获取开机画面存放路径
    public static String bootAnimationAction(Context ctx,int flag) {
        final String XH = "XHZY",HC = "zim";
        String board = SystemPropertiesReflection.USER;
        if (flag == 2) {
            downloadAnimation(ctx);
            return "success:"+flag;
        } else
        if (flag == 1) {
            downloadAnimation(ctx);
            return "success:"+flag;
        } else
        if (flag == 0) {
            if (board.equals(XH)) clearAnimation(ctx);
            if (board.equals(HC)) setAnimationByRoot(ctx,0);
            return "success:"+flag;
        } else
        if (flag == -1) {
            String bootAnimationDir = "/system/media/";
            if (board.equals(XH)) bootAnimationDir = "/data/local/";
            if (board.equals(HC)) bootAnimationDir = "/odm/media/";
            return bootAnimationDir;
        } else return "";
    }

    // 下载开机画面
    public static void downloadAnimation(Context ctx) {
        String url = "http://192.168.6.86:8086/xiazaiba/bootanimation/bootanimation.zip";
        String name = "ba.zip";
        downLoad(ctx,url,name,"bootanimation",false);
    }

    // 开机画面路径（不同主板路径不同）
    public static String getBootAnimationPath() {
        return bootAnimationAction(null,-1);
    }

    // 通过root权限设置（华诚3568）
    public static void setAnimationByRoot(Context ctx,int flag) {
        String r = "";
        r = runCommandSu("root");
        if (r.equals("")) {
            r = runCommandSu("remount");
            if (r.equals("remount succeeded")) {
                if (flag == 1) setAnimation(ctx);
                if (flag == 0) clearAnimation(ctx);
            } else showToast(ctx, "当前设备型号不支持开机画面设置："+r);
        } else showToast(ctx, "当前设备型号不支持开机画面设置："+r);
    }

    // 设置开机画面
    public static void setAnimation(Context ctx) {
        String baPath = "/sdcard/Download/ba.zip";
        if (isExists("/sdcard/Download/","ba.zip")) {
            String r = runCommandSu("cp "+baPath+" "+getBootAnimationPath()+"bootanimation.zip");
            if (r.equals("")) {
                r = runCommandSu("chmod 0755 "+getBootAnimationPath()+"bootanimation.zip");
                if (r.equals("")) {
                    r = runCommandSu("du -h "+getBootAnimationPath()+"bootanimation.zip");
                    String msg = r.equals("")?"开机画面设置失败":"开机画面设置成功:"+r+"，重启后生效";
                    msg = r.equals("")?"开机画面设置失败":"开机画面设置成功，重启后生效";
                    showToast(ctx,msg);
                    delFile(baPath);
                } else showToast(ctx,r);
            } else showToast(ctx,r);
        } else showToast(ctx,"开机画面文件不存在");
    }

    //清除开机画面
    public static void clearAnimation(Context ctx) {
        String command = "rm -f "+getBootAnimationPath()+"bootanimation.zip";
        String r = runCommandSu(command);
        MyUtil.showLog("clearAnimation", r);
        if (r.equals("")) showToast(ctx,"开机画面清除成功，重启后生效");
        else showToast(ctx,"开机画面清除失败，"+r);
    }

    // 显示toast
    public static void showToast(Context ctx,String s) {
        Toast.makeText(ctx, s, Toast.LENGTH_LONG).show();
    }

    public static String runCommandSu(String command) {
        Process process = null;
        String result = "";
        DataOutputStream os = null;
        DataInputStream is = null;
        try {
            MyUtil.showLog("runCommandSu",command);
            process = Runtime.getRuntime().exec("su");
            os = new DataOutputStream(process.getOutputStream());
            is = new DataInputStream(process.getInputStream());
            os.writeBytes(command + "\n");
            os.writeBytes("exit\n");
            os.flush();
            String line = null;
            while ((line = is.readLine()) != null) {
                result += line;
            }
            int exit = process.waitFor();
            process.destroy();
            if (exit == 0) {
                //System.out.println("子进程正常完成1111111111111");
            } else {
                result = result + "runCommandSu进程异常结束，exit="+exit;
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
            result = e.getMessage();
        } catch (IOException e) {
            e.printStackTrace();
            result = e.getMessage();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (process != null) {
                process.destroy();
            }
        }
        return result;
    }

    public static Boolean isExists(String path, String fileName) {
        File file = new File(path,fileName);
        if (fileName.equals("")) {
            file = new File(path);
        }
        MyUtil.showLog(fileName, file);
        return file.exists();
    }
}
